
#import "AppDelegate.h"

#import "VisitingMessageViewController.h"

#import "UIImageView+FIDAnimation.h"
#if defined(P2PWEXVS)
#define MAX_SHOW_TIME_SEC       30
#else
#define MAX_SHOW_TIME_SEC       22
#endif

#define MAX_LOAD_IMG_TIME_SEC   20
#define LOAD_IMG_USEC           500*1000

//#define IMAG_MYSERVER_PATH  @"http://112.124.112.116/DOOR_Server/pic_uploads"
////#define IMAG_MYSERVER_PATH  @"http://112.124.112.116/DOOR_Server/pic_uploads/12345678901234567890/1"

#if defined(P2PWEXVS)

#else
#define IMAG_MYSERVER_PATH              @"http://112.124.112.116/DOOR_Server/showpic.php"
//#define IMAG_MYSERVER_PATH  @"http://112.124.112.116/DOOR_Server/showpic.php?cmd=showpic&devid=12345678901234567890&eventpicn=picname"
#endif

@interface VisitingMessageViewController ()

@end

@implementation VisitingMessageViewController

@synthesize isRunningConnectingThread;
@synthesize connectThread;
@synthesize connectThreadLock;

@synthesize isRunningStartingThread;
@synthesize startThread;
@synthesize startThreadLock;

@synthesize uidUserInfo;
@synthesize typeUserInfo;
@synthesize timeUserInfo;
@synthesize picnUserInfo;
@synthesize aliasUserInfo;
@synthesize devidUserInfo;

- (void)timerShow:(NSTimer *)timer {
    showTimes += 1;
    NSLog(@"vvvvvvvvvvvvvvvvv timerShow vvvvvvvvvvvvvvvvv showTimes:%ld", (long)showTimes);
    
    if (showTimes >= MAX_SHOW_TIME_SEC) {
        [self selectIgnore:nil];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
#if defined(STYLE_BLUE_AIC)
    //hzx set color
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg_blue_m.png"] forBarMetrics:UIBarMetricsDefault];
    
#elif defined(STYLE_ORANGE_AIC)
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg_orange.png"] forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:255.0f/255 green:255.0f/255 blue:255.0f/255 alpha:1]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:1]}];
#else
    
#if defined(P2PNEX)
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:254.0f/255 green:195.0f/255 blue:64.0f/255 alpha:1.0f]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1]}];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nex_bg_nav0.png"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage imageNamed:@"nex_bg_line.png"];
#else
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:255.0f/255 green:125.0f/255 blue:255.0f/255 alpha:1]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1]}];
#endif
    
#endif
    
    /*
     NSString *title = [[NSString alloc] initWithString:NSLocalizedString(@"Visiting Message", @"")];
     self.navigationItem.title = title;
     [title release];
     */
    /*
     UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
     initWithTitle:@" "
     style:UIBarButtonItemStylePlain
     target:self
     action:@selector(back:)];
     #if defined(P2PNEX)
     [backButton setImage:[UIImage imageNamed:@"nex_back3%.png"]];
     #else
     [backButton setImage:[UIImage imageNamed:@"_back%3x.png"]];
     #endif
     self.navigationItem.leftBarButtonItem = backButton;
     [backButton release];
     */
    

    
    //[self.view addSubview:savePasswordcheck];
    
    //self.picnScrollView.contentMode = UIViewContentModeScaleAspectFit; // 1:1
    //self.picnImageView.contentMode = UIViewContentModeScaleAspectFit; // 1:1
    
    
    self.picnScrollView.minimumZoomScale = ZOOM_MIN_SCALE;
    self.picnScrollView.maximumZoomScale = ZOOM_MAX_SCALE;
    self.picnScrollView.contentMode = UIViewContentModeScaleAspectFit;
    self.picnScrollView.contentSize = self.picnScrollView.frame.size;
    
    isLoginOver = NO;
    isMove = NO;
    
 /*   self.uidLab.text = [NSString stringWithFormat:@"%@:", NSLocalizedString(@"UID", @"")];
    self.aliasLab.text = [NSString stringWithFormat:@"%@:", NSLocalizedString(@"Alias", @"")];
    self.typeLab.text = [NSString stringWithFormat:@"%@:", NSLocalizedString(@"Type", @"")];
    self.devidLab.text = [NSString stringWithFormat:@"%@:", NSLocalizedString(@"ID", @"")];
    self.devTimeLab.text = [NSString stringWithFormat:@"%@:", NSLocalizedString(@"Time", @"")];
    
    self.ignoreLabel.text = NSLocalizedString(@"Ignore", @"");
    self.answeringLabel.text = NSLocalizedString(@"Answering", @"");
    */
    showTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerShow:) userInfo:nil repeats:YES];
    showTimes = 0;
    [showTimer setFireDate:[NSDate distantFuture]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    [showTimer setFireDate:[NSDate distantPast]];
    showTimes = 0;
    
    isHideView = NO;
    
    NSLog(@"uidUserInfo:%@", uidUserInfo);
    NSLog(@"typeUserInfo:%ld", (long)typeUserInfo);
    NSLog(@"timeUserInfo:%ld", (long)timeUserInfo);
    NSLog(@"picnUserInfo:%@", picnUserInfo);
    
    [self initSound:typeUserInfo];
    
    
    [self typeLabelSetting:typeUserInfo];
    
    //self.titleLabel.text = NSLocalizedString(@"Visiting Message", @"");
    self.uidLabel.text = self.uidUserInfo;
    self.aliasLabel.text = self.aliasUserInfo;
    self.devidLabel.text = self.devidUserInfo;
    
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:timeUserInfo];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    //[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
    
    self.devTimeLabel.text = [dateFormatter stringFromDate:date];
    
    [self.picnImageView pointAnimationWithFileName:@"icon_small_bell" imageCount:3];
    

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    
    [showTimer setFireDate:[NSDate distantFuture]];
    
    isHideView = YES;
    
    [AppDelegate globalDelegate].isShowVisitingMessageViewC = NO;
    
    AudioServicesDisposeSystemSoundID(shake_sound_male_id);
    NSLog(@"AudioServicesDisposeSystemSoundID(shake_sound_male_id)");
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    NSString *imgUrl = [NSString stringWithFormat:@"%@?cmd=showpic&devid=%@&eventpicn=%@", IMAG_MYSERVER_PATH, self.uidUserInfo, self.picnUserInfo];
    
    [self loadImageFromServer:imgUrl];
    
#if defined(P2PWEXVS)
    imgUrl = [NSString stringWithFormat:@"%@?cmd=showpic&devid=%@&eventpicn=%@", IMAG_MYSERVER_PATH_0, self.uidUserInfo, self.picnUserInfo];
    
    [self loadImageFromServer:imgUrl];
#endif
    
    
    //dispatch_sync(dispatch_get_main_queue(), ^{
    //});
    
    
    AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
    NSLog(@"AudioServicesPlaySystemSound shake_sound_male_id");
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
    
    dispatch_queue_t queue2 = dispatch_queue_create("load_image", NULL);
    dispatch_async(queue2, ^{
        
        for (int i=0; i<MAX_SHOW_TIME_SEC/2; i++) {
            if (!isHideView) {
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
                
                usleep(2*1000*1000);
            } else {
                break;
            }
        }
        
    });
    
    [AppDelegate globalDelegate].isShowVisitingMessageViewC = YES;
}


- (BOOL)shouldAutorotate {
    NSLog(@"VisitingMessageViewController -----------------  shouldAutorotate");
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    NSLog(@"VisitingMessageViewController -----------------  supportedInterfaceOrientations");
    return UIInterfaceOrientationMaskPortrait;
}

/*
 - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
 NSLog(@"VisitingMessageViewController -----------------  preferredInterfaceOrientationForPresentation");
 return UIInterfaceOrientationMaskPortrait;
 }
 */

- (void)loadImageFromServer:(NSString *)imgUrl {
    
    NSLog(@"loadImageFromServer imgUrl:%@", imgUrl);
    //#define IMAG_MYSERVER_PATH  @"http://112.124.112.116/DOOR_Server/showpic.php?cmd=showpic&devid=12345678901234567890&eventpicn=picname"
    
    [self.loadingImgActivityIndicatorView setHidden:NO];
    [self.loadingImgActivityIndicatorView startAnimating];
    
    dispatch_queue_t queue = dispatch_queue_create("load_image", NULL);
    dispatch_async(queue, ^{
        
        NSLog(@"self.picnImageView.image begin dispatch_get_main_queue!");
        //self.picnImageView.image = (self.picnUserInfo != nil && (![self.picnUserInfo isEqualToString:@""])) ? [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]]] : [UIImage imageNamed:@"videoClip.png"];
        
        for (int i=0; i<MAX_LOAD_IMG_TIME_SEC; i++) {
            
            NSLog(@"isHideView:%d", isHideView);
            if (isHideView) {
                break;
            }
            
            NSURL *url = [NSURL URLWithString:imgUrl];
            
            /*
             NSLog(@"scheme:%@", [url scheme]); //协议 http
             NSLog(@"host:%@", [url host]);     //域名 www.baidu.com
             NSLog(@"absoluteString:%@", [url absoluteString]); //完整的url字符串             NSLog(@"relativePath: %@", [url relativePath]); //相对路径 search
             NSLog(@"port :%@", [url port]);  // 端口 8080
             NSLog(@"path: %@", [url path]);  // 路径 search
             NSLog(@"pathComponents:%@", [url pathComponents]); // search
             NSLog(@"Query:%@", [url query]);  //参数 id=1
             */
            
            if (url) {
                NSLog(@"url:%@", url);
                NSData *data = [NSData dataWithContentsOfURL:url];
                
                if (data) {
                    NSLog(@"[data length]:%lu", (unsigned long)[data length]);
                    
                    UIImage *img = [UIImage imageWithData:data];
                    
                    if (img) {
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            self.picnImageView.image = img;
                        });
                        
                        break;
                    } else {
                        NSLog(@"img == nil; i=%d", i);
                        
                        usleep(LOAD_IMG_USEC);
                    }
                    
                } else {
                    NSLog(@"data == nil; i=%d", i);
                    
                    usleep(LOAD_IMG_USEC);
                }
            } else {
                NSLog(@"imgUrl == nil; i=%d", i);
                
                usleep(LOAD_IMG_USEC);
            }
            
            
        }
        
        
        NSLog(@"self.picnImageView.image over dispatch_get_main_queue!");
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            [self.loadingImgActivityIndicatorView stopAnimating];
            [self.loadingImgActivityIndicatorView setHidden:YES];
        });
        
        NSLog(@"self.picnImageView.image over!");
        
    });
}

#pragma mark - RegisterViewDelegate Methods
- (void)didRegisterReturn:(NSInteger)value {
    
    NSLog(@"didRegisterReturn value:%ld", (long)value);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Message", @"") message:NSLocalizedString(@"Successful", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil];
    [alert show];
}


//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    //CGRect frame = textField.frame;
    
    if (isMove) {
        return;
    }
    
    CGRect frame = self.loginButton.frame;
    
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
    
    NSLog(@"offset:%d", offset);
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0) {
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
        isMove = YES;
    }
    
    [UIView commitAnimations];
}

//当用户按下return键或者按回车键，keyboard消失
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    isMove = NO;
    
    [textField resignFirstResponder];
    return YES;
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (isMove) {
        return;
    }
    
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}

- (BOOL)verificationCheck {
    NSString *accountText;
    NSString *passwordText;
    
    if (self.accountTextField != nil) accountText = self.accountTextField.text;
    if (self.passwordTextField != nil) passwordText = self.passwordTextField.text;
    
    if ([accountText length] == 0) {
        
#if 0
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Warning", @"") message:NSLocalizedString(@"Please input account", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil];
        [alert show];
        [alert release];
#else
    //    [[iToast makeText:NSLocalizedString(@"Please input account", @"")] show2];
#endif
        
        return NO;
    }
    
    if ([passwordText length] == 0) {
        
#if 0
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Warning", @"") message:NSLocalizedString(@"Please input the password", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil];
        [alert show];
        [alert release];
#else
    //    [[iToast makeText:NSLocalizedString(@"Please input password", @"")] show2];
#endif
        
        return NO;
    }
    
    return YES;
}

- (IBAction)selectLogin:(id)sender {
    NSLog(@"selectLogin 1");
    
    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    isMove = NO;
    
    if (![self verificationCheck]) {
        return;
    }
    
    if (self.navigationController == nil) {
        NSLog(@"self.navigationController == nil");
    }
    

    
}


/*
 - (IBAction)selectRegister:(id)sender {
 RegisterViewController * controller = [[RegisterViewController alloc] init];
 controller.delegate = self;
 [self.navigationController pushViewController:controller animated:YES];
 //[self presentViewController:controller animated:YES completion:^{
 
 //}];
 [controller release];
 }
 
 - (IBAction)selectResetPassword:(id)sender {
 ResetPasswordViewController * controller = [[ResetPasswordViewController alloc] init];
 
 controller.userid = self.accountTextField.text;
 
 [self.navigationController pushViewController:controller animated:YES];
 //[self presentViewController:controller animated:YES completion:^{
 
 //}];
 [controller release];
 }
 */
- (IBAction)selectIgnore:(id)sender {
    NSLog(@"selectIgnore");
    
    [AppDelegate globalDelegate].isShowVisitingMessageViewC = NO;
    // Go to main view
    [self dismissModalViewControllerAnimated:NO];
}

- (IBAction)selectAnswering:(id)sender {
    NSLog(@"selectAnswering");
    
#if defined(DOOR_TEST)
#else
    /**
     **/
    // set global
    //NSArray *keys=[NSArray arrayWithObjects:@"uid", @"type", @"time", @"picn", nil];
    //NSArray *objects=[NSArray arrayWithObjects:self.uidUserInfo, self.typeUserInfo, self.timeUserInfo, self.picnUserInfo, nil];
    NSArray *keys=[NSArray arrayWithObjects:@"uid", nil];
    NSArray *objects=[NSArray arrayWithObjects:self.uidUserInfo, nil];
    NSDictionary *dic=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GetPushNotification" object:self userInfo:dic];
#endif
    
    [AppDelegate globalDelegate].isShowVisitingMessageViewC = NO;
    
    // Go to main view
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)selectSavePassword:(id)sender {
    NSLog(@"selectSavePassword");
}



#pragma mark - Threading

- (void)loopConnect {
    
    self.isRunningConnectingThread = TRUE;
    
    if (connectThread == nil) {
        connectThreadLock = [[NSConditionLock alloc] initWithCondition:NOTDONE];
        connectThread = [[NSThread alloc] initWithTarget:self selector:@selector(doLoopConnect) object:nil];
        [connectThread start];
    }
    
    [self loopStart];
}

- (void)loopConnect2 {
    
    for(int i=0; i < [[AppDelegate globalDelegate].camera_list count]; i++) {
        MyCamera *camera = [[AppDelegate globalDelegate].camera_list objectAtIndex:i];
        NSString *camerauid = [[AppDelegate globalDelegate].camera_uid_list objectAtIndex:i];
        //for (MyCamera *camera in camera_list) {
        
        {
            NSLog(@"loopConnect2 clflvc for begin! camera.sessionState:%ld", (long)camera.sessionState);
            
            //[camera disconnect];
            if (camera.sessionState != CONNECTION_STATE_CONNECTED)
                [camera connect:camerauid];
            
            NSLog(@"loopConnect2 clflvc for end!");
        }
        
    }
    
    [self loopStart2];
}


- (void)doLoopConnect {
    
    
    //usleep(500 * 1000);
    
    [connectThreadLock lock];
    
    //LOG(@"=== Connect Thread Start (%@) ===", uid);
    
#if defined(P2PNETCAM_HAIER)
    for(int i=0; i < [self.position_camera_list count]; i++) {
        MyCamera *camera = [self.position_camera_list objectAtIndex:i];
        //for (MyCamera *camera in self.position_camera_list) {
#else
        for(int i=0; i < [[AppDelegate globalDelegate].camera_list count]; i++) {
            MyCamera *camera = [[AppDelegate globalDelegate].camera_list objectAtIndex:i];
            NSString *camerauid = [[AppDelegate globalDelegate].camera_uid_list objectAtIndex:i];
            //for (MyCamera *camera in camera_list) {
#endif
            
            
            if (self.isRunningConnectingThread)
            {
                NSLog(@"1 clflvc for begin!");
                
                //[camera disconnect];
                if (camera.sessionState != CONNECTION_STATE_CONNECTED)
                    [camera connect:camerauid];
                
                usleep(LOOP_USLEEP / 100);
                
                NSLog(@"2 clflvc for end!");
            }
            else
            {
                break;
            }
        }
        
        
        
        //LOG(@"=== Connect Thread Exit (%@) ===", uid);
        
        [connectThreadLock unlockWithCondition:DONE];
        
        
        self.isRunningConnectingThread = FALSE;
    }
    
    - (void)disLoopConnect
    {
        [self disLoopStart];
        
        if (connectThread != nil) {
            
            NSLog(@"disLoopConnect!!!!!!!!!!!");
            
            self.isRunningConnectingThread = FALSE;
            
            [connectThreadLock lockWhenCondition:DONE];
            [connectThreadLock unlock];

            connectThread = nil;
        }
    }
    
    - (void)loopStart {
        NSLog(@"VisitingMessageViewController clflvc loopStart............");
        self.isRunningStartingThread = TRUE;
        
        if (startThread == nil) {
            startThreadLock = [[NSConditionLock alloc] initWithCondition:NOTDONE];
            startThread = [[NSThread alloc] initWithTarget:self selector:@selector(doLoopStart) object:nil];
            [startThread start];
        }
    }
    
    - (void)loopStart2 {
        
        for(int i=0; i < [[AppDelegate globalDelegate].camera_list count]; i++) {
            MyCamera *camera = [[AppDelegate globalDelegate].camera_list objectAtIndex:i];
           // NSString *camerauid = [[AppDelegate globalDelegate].camera_uid_list objectAtIndex:i];
            //for (MyCamera *camera in camera_list) {
            
            {
                NSLog(@"loopStart2 clflvc for begin! [camera getConnectionStateOfChannel:0]:%ld", (long)[camera getConnectionStateOfChannel:0]);
                
                if ([camera getConnectionStateOfChannel:0] != CONNECTION_STATE_CONNECTED) {
                    NSLog(@"([camera getConnectionStateOfChannel:0] != CONNECTION_STATE_CONNECTED)");
                    
                    [camera start:0];
                    
                    SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                    s->channel = 0;
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                    free(s);
                    
                    SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
                    free(s2);
                    
                    SMsgAVIoctrlSetTimeReq *s3 = (SMsgAVIoctrlSetTimeReq *)malloc(sizeof(SMsgAVIoctrlSetTimeReq));
                    s3->time_second_0zone_ = [[NSDate date] timeIntervalSince1970];
                    s3->diff_zone_minites_ = [[NSTimeZone localTimeZone] secondsFromGMT] / 60;
                    
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_TIME_REQ Data:(char *)s3 DataSize:sizeof(SMsgAVIoctrlSetTimeReq)];
                    free(s3);
                    NSLog(@"sendIOCtrlToChannel IOTYPE_USER_IPCAM_SET_TIME_REQ(uid:%@)", camera.uid);
                }
                
                NSLog(@"loopStart2 clflvc for end!");
            }
            
        }
        
    }
    
    
    - (void)doLoopStart {
        
        
        //usleep(500 * 1000);
        
        [startThreadLock lock];
        
        NSLog(@"=== clflvc doLoopStart Thread Waite Connect Over  ===");
        
        while(self.isRunningConnectingThread) {
            usleep(100 * 1000);
            NSLog(@"=== self.isRunningConnectingThread  usleep(100 * 1000); ===");
            continue;
        }
        
        BOOL isAllConnected = NO;
        int index = 0;
        while(!isAllConnected && [[AppDelegate globalDelegate].camera_list count] > 0) {
            for(int i=0; i < [[AppDelegate globalDelegate].camera_list count]; i++) {
                MyCamera *camera = [[AppDelegate globalDelegate].camera_list objectAtIndex:i];
          //      NSString *camerauid = [[AppDelegate globalDelegate].camera_uid_list objectAtIndex:i];
                //for (MyCamera *camera in camera_list) {
                
                if (camera.sessionState == CONNECTION_STATE_CONNECTING) {
                    NSLog(@"camera(%@).sessionState == CONNECTION_STATE_CONNECTING", camera.uid);
                    
                    isAllConnected = NO;
                    index = i;
                    usleep(100 * 1000);
                    
                    break;
                } else {
                    isAllConnected = YES;
                }
                
                usleep(200 * 1000);
                
            }
        }
        
        NSLog(@"=== clflvc doLoopStart Thread Start  ===");
        
#if defined(P2PNETCAM_HAIER)
        for(int i=0; i < [self.position_camera_list count]; i++) {
            MyCamera *camera = [self.position_camera_list objectAtIndex:i];
            //for (MyCamera *camera in self.position_camera_list) {
#else
            for(int i=0; i < [[AppDelegate globalDelegate].camera_list count]; i++) {
                MyCamera *camera = [[AppDelegate globalDelegate].camera_list objectAtIndex:i];
                //for (MyCamera *camera in camera_list) {
#endif
                
                
                if (self.isRunningStartingThread)
                {
                    NSLog(@"1 clflvc for begin!");
                    
                    if ([camera getConnectionStateOfChannel:0] != CONNECTION_STATE_CONNECTED) {
                        NSLog(@"([camera getConnectionStateOfChannel:0] != CONNECTION_STATE_CONNECTED)");
                        
                        [camera start:0];
                        
                        SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                        s->channel = 0;
                        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                        free(s);
                        
                        SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
                        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
                        free(s2);
                        
                        SMsgAVIoctrlSetTimeReq *s3 = (SMsgAVIoctrlSetTimeReq *)malloc(sizeof(SMsgAVIoctrlSetTimeReq));
                        s3->time_second_0zone_ = [[NSDate date] timeIntervalSince1970];
                        s3->diff_zone_minites_ = [[NSTimeZone localTimeZone] secondsFromGMT] / 60;
                        
                        [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_TIME_REQ Data:(char *)s3 DataSize:sizeof(SMsgAVIoctrlSetTimeReq)];
                        free(s3);
                        NSLog(@"sendIOCtrlToChannel IOTYPE_USER_IPCAM_SET_TIME_REQ(uid:%@)", camera.uid);
                    }
                    
                    usleep(LOOP_USLEEP / 100);
                    
                    NSLog(@"2 clflvc for end!");
                }
                else
                {
                    break;
                }
            }
            
            NSLog(@"=== clflvc doLoopStart Thread Exit ===");
            
            [startThreadLock unlockWithCondition:DONE];
            
            
            self.isRunningStartingThread = FALSE;
        }
        
        - (void)disLoopStart
        {
            if (startThread != nil) {
                
                NSLog(@"clflvc disLoopStart!!!!!!!!!!!");
                
                self.isRunningStartingThread = FALSE;
                
                [startThreadLock lockWhenCondition:DONE];
                [startThreadLock unlock];
                
                startThread = nil;
            }
        }
        
#pragma mark - Sound
        - (void)initSound:(NSInteger)type
        {
            
            
            NSString *path;
            
            switch (type) {
                case AVIOCTRL_EVENT_ALL:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case AVIOCTRL_EVENT_EXPT_REBOOT:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case AVIOCTRL_EVENT_IOALARM:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                    //case AVIOCTRL_EVENT_IOALARMPASS:
                    //    break;
                    
                case AVIOCTRL_EVENT_MOTIONDECT:
#if defined(P2PWEXVS)
                    path = [[NSBundle mainBundle] pathForResource:@"ydzc60" ofType:@"aac"];
#else
                    path = [[NSBundle mainBundle] pathForResource:@"ydzc" ofType:@"aac"];
#endif
                    
                    break;
                    
                    //case AVIOCTRL_EVENT_MOTIONPASS:
                    //    break;
                    
                case AVIOCTRL_EVENT_SDFAULT:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case AVIOCTRL_EVENT_VIDEOLOST:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case AVIOCTRL_EVENT_VIDEORESUME:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_DOOR_BELL:
                    path = [[NSBundle mainBundle] pathForResource:@"db20" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_ALARM_INFRARED:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_ALARM_SMOKING:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_ALARM_AIR:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_ALARM_REMOTE:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_ALARM_DOOR_WINDOW:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_ALARM_WHISTLE:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_PIR_WARNING:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_ALARM_SWITCH:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
                    
                case USER_EVENT_SAFEBOX_HOSTAGE:
                    path = [[NSBundle mainBundle] pathForResource:@"alarm30" ofType:@"aac"];
                    break;
                case USER_EVENT_SAFEBOX_DOOR_ERROR:       // for safebox door error
                    path = [[NSBundle mainBundle] pathForResource:@"alarm30" ofType:@"aac"];
                    break;
                    
                default:
                    path = [[NSBundle mainBundle] pathForResource:@"gpio" ofType:@"aac"];
                    break;
            }
            
            
            
            if (path) {
                shake_sound_male_id = 0;
                
                //注册声音到系统
                AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&shake_sound_male_id);
                //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
            }
        }
        
        - (void)typeLabelSetting:(NSInteger)type {
            
            switch (type) {
                case AVIOCTRL_EVENT_ALL:
                   // self.typeLabel.text = NSLocalizedString(@"Full-time recording", @"");
                    self.typeLabel.text = @"全时录像";
                    break;
                    
                case AVIOCTRL_EVENT_EXPT_REBOOT:
                   // self.typeLabel.text = NSLocalizedString(@"Reboot", @"");
                    self.typeLabel.text = @"重新启动";
                    break;
                    
                case AVIOCTRL_EVENT_IOALARM:
                  //  self.typeLabel.text = NSLocalizedString(@"IO Alarm", @"");
                    self.typeLabel.text = @"IO报警";
                    break;
                    
                    //case AVIOCTRL_EVENT_IOALARMPASS:
                    //    break;
                    
                case AVIOCTRL_EVENT_MOTIONDECT:
                 //   self.typeLabel.text = NSLocalizedString(@"Motion Detection", @"");
                    self.typeLabel.text = @"移动侦测";
                    break;
                    
                    //case AVIOCTRL_EVENT_MOTIONPASS:
                    //    break;
                    
                case AVIOCTRL_EVENT_SDFAULT:
                  //  self.typeLabel.text = NSLocalizedString(@"SDCard Fault", @"");
                    self.typeLabel.text = @"SDCard错误";
                    break;
                    
                case AVIOCTRL_EVENT_VIDEOLOST:
                  //  self.typeLabel.text = NSLocalizedString(@"Video Lost", @"");
                    self.typeLabel.text = @"视频遗失";
                    break;
                    
                case AVIOCTRL_EVENT_VIDEORESUME:
                    //self.typeLabel.text = NSLocalizedString(@"Video Resume", @"");
                    self.typeLabel.text = @"视频回复";
                    break;
                    
                case USER_EVENT_DOOR_BELL:
//                    self.typeLabel.text = NSLocalizedString(@"Door Bell", @"");
                    self.typeLabel.text = @"门铃提醒";
                    break;
                    
                case USER_EVENT_ALARM_INFRARED:
                 //   self.typeLabel.text = NSLocalizedString(@"Infrared", @"");
                    self.typeLabel.text = @"红外";
                    break;
                    
                case USER_EVENT_ALARM_SMOKING:
                    self.typeLabel.text = NSLocalizedString(@"Smoke Sensor", @"");
                    break;
                    
                case USER_EVENT_ALARM_AIR:
                    self.typeLabel.text = NSLocalizedString(@"Gas Sensor", @"");
                    break;
                    
                case USER_EVENT_ALARM_REMOTE:
                    self.typeLabel.text = NSLocalizedString(@"Remote Control", @"");
                    break;
                    
                case USER_EVENT_ALARM_DOOR_WINDOW:
                    self.typeLabel.text = NSLocalizedString(@"Door Sensor", @"");
                    break;
                    
                case USER_EVENT_ALARM_WHISTLE:
                    self.typeLabel.text = NSLocalizedString(@"Siren", @"");
                    break;
                    
                case USER_EVENT_PIR_WARNING:
                    self.typeLabel.text = NSLocalizedString(@"Door Alarm", @"");
                    break;
                    
                case USER_EVENT_ALARM_SWITCH:
                    self.typeLabel.text = NSLocalizedString(@"Switch", @"");
                    break;
                case USER_EVENT_SAFEBOX_DOOR_OPENED:       // for safebox door opened
                    self.typeLabel.text = NSLocalizedString(@"Door Opened", @"");
                    break;
                case USER_EVENT_SAFEBOX_DOOR_ERROR:       // for safebox door error
                    self.typeLabel.text = NSLocalizedString(@"Anti-theft Alarmed", @"");
                    break;
                    
                case USER_EVENT_SAFEBOX_HOSTAGE:
                    self.typeLabel.text = NSLocalizedString(@"Hijack alarm", @"");
                    break;
                    
                    
                default:
                    self.typeLabel.text = NSLocalizedString(@"Other", @"");
                    break;
            }
            
        }
        
#pragma mark - ScrollView Delegate
        /*
         - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
         //NSLog(@"viewForZoomingInScrollView scrollView:%@", scrollView);
         if (self.interfaceOrientation == UIInterfaceOrientationPortrait) {
         return self.monitorPortrait;
         }
         else if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
         self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
         return self.monitorLandscape;
         }
         else return nil;
         }
         
         - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView
         withView:(UIView *)view
         atScale:(float)scale
         {
         if (scale == ZOOM_MIN_SCALE) {
         
         if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
         self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
         
         self.scrollViewLandscape.contentSize = CGSizeMake(320, 240);
         }
         else {
         self.scrollViewPortrait.contentSize = CGSizeMake(320, 240);
         }
         }
         }
         */
        @end
